package com.david.config.filter;

import com.david.common.exception.TokeneException;
import com.david.common.utils.JwtUtils;
import com.david.common.utils.ResultUtils;
import com.david.common.utils.SpringContextUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;


public class JwtAuthorizationFilter extends BasicAuthenticationFilter { //原版

    public JwtAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws  IOException, ServletException {

        try {
            System.out.println(request.toString());
             // 检查请求头中是否有token
            String jwtToken = request.getHeader("token");
            System.out.println(jwtToken);
            if (!StringUtils.hasLength(jwtToken)) {
                System.out.println("---------------不包含token，进入doFilter方法------------");
                chain.doFilter(request, response);
                return;
            }
            // 过滤器中无法初始化Bean组件，使用上下文获取
            JwtUtils jwtUtils = SpringContextUtils.getBean("jwtUtils");
            if (jwtUtils == null) {
                throw new TokeneException("用户未登录");
            }
            // 解析令牌
            Claims claims;
            try {
                claims = jwtUtils.parseJwt(jwtToken);
            } catch (Exception ex) {
                throw new TokeneException("凭证已过期，请重新登录");
            }
            //获取用户信息
            String username = (String) claims.get("username");
            String authorityString = (String) claims.get("authorityString");

            Authentication authentication = new UsernamePasswordAuthenticationToken(
                    username, null, Collections.singleton(new SimpleGrantedAuthority(authorityString))
            );
            // 将用户信息放入SecurityContext上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);

        }catch (Exception ex) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            String value = new ObjectMapper().writeValueAsString(ResultUtils.fail(false,ex.getMessage()));
            response.getWriter().write(value);
        }
    }
}
